import axios from 'axios';
import { message } from 'antd';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

const baseUrl = 'http://xawn.f3322.net:8012';

// 请求拦截器
axios.interceptors.request.use(
  (config) => {
    const token = localStorage.token;
    config.headers['content-type'] = 'application/x-www-form-urlencoded';
    config.url = baseUrl + config.url;
    config.headers.Authentication =
      'b25e39b47e774b4a05b3cb1555fc377f209457c3fd339d373d3fca7b1ea8be56fdc6ed05b7ffb0700e7300d242fb83b5a46edc99fa3a814536d09c33ffd30895c2f2c5bb1aee065129db0544f0697636c994b316f67706f382145fcfc12e60d1c405a570d0028e40987ec7a4e7a8ba1b2e0bcb73e260a75609666cc8c47d40254f2ba291a802f28f';
    if (token) {
      config.headers.Authentication = token.replace(/\"/g, '');
    }
    // let token = localStorage.token
    // if (token) {
    //   config.headers.token = token
    // }
    NProgress.start();
    // 在请求拦截器，return结果才会继续往后执行
    return config;
  },
  (err) => {
    Promise.reject(err);
  },
);

// 提供响应拦截器
axios.interceptors.response.use(
  (resp) => {
    NProgress.done();
    return resp;
  },
  (err) => {
    // 处理服务器返回的各种异常,异常结果
    const response = err.response;
    if (response) {
      switch (response.status) {
        case 500:
          message.error('服务器异常，稍后再试');
          break;
        case 401:
          message.error('身份认证过期，请重新登录');
          localStorage.removeItem('userInfo');
          localStorage.removeItem('token');
          // 跳转回登录
          window.location.href = '/login';
          break;
        case 404:
          message.error('请求路径发生变化');
          break;
      }
    }

    // return Promise.reject(err);
    return err;
  },
);
